package com.bk.bands;

import java.io.InputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;

import com.bk.bands.model.Template;
import com.bk.bands.template.XmlBand;
import com.bk.bands.template.XmlBorder;
import com.bk.bands.template.XmlFields;
import com.bk.bands.template.XmlFont;
import com.bk.bands.template.XmlPosition;
import com.bk.bands.template.XmlShape;
import com.bk.bands.template.XmlStyle;
import com.bk.bands.template.XmlStyles;
import com.bk.bands.template.XmlTemplate;
import com.bk.bands.template.XmlTemplateFactory;
import com.bk.bands.template.XmlText;
import com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl;

/**
 * Created by IntelliJ IDEA.
 * User: SG0891787
 * Date: 3/27/12
 * Time: 11:21 AM
 */
public class TemplateUnmarshaller
{
   private Class[] classesToBound = new Class[]
   {
      XmlStyle.class,
      XmlBorder.class,
      XmlStyles.class,
      XmlFont.class,
      XmlText.class,
      XmlShape.class,
      XmlFields.class,
      XmlBand.class,
      XmlTemplate.class,
      XmlPosition.class
   };

   private JAXBContext jaxbContext;

   private JAXBContext getJaxbContext() throws JAXBException
   {
      if(jaxbContext == null)
      {
         jaxbContext = JAXBContext.newInstance(classesToBound);
      }
      return jaxbContext;
   }

   public Template unmarshal(InputStream templateXml) throws JAXBException
   {
      XmlTemplateFactory templateFactory = new XmlTemplateFactory(new XmlTemplate());
      Unmarshaller unmarshaller = getJaxbContext().createUnmarshaller();
      unmarshaller.setProperty(UnmarshallerImpl.FACTORY,templateFactory);
      unmarshaller.setEventHandler(new ValidationEventHandler()
                                    {
                                       public boolean handleEvent(ValidationEvent event)
                                       {
                                          return false;
                                       }
                                    });

      XmlTemplate xmlTemplate = (XmlTemplate) unmarshaller.unmarshal(templateXml);
      return xmlTemplate.getTemplate();
   }
}
